package com.enzoism.springboot.quartz.config;

import com.enzoism.springboot.quartz.job.HelloJob;
import com.enzoism.springboot.quartz.job.QuartzJob;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @Description: 配置Quartz的Scheduler调度器
 * @Author devin.jiang
 * @CreateDate 2019/5/19 20:10
 */
@Configuration
public class QuartzJobConfigure2 {

    /**
     * 使用JobDetail
     * @return
     */
    @Bean("jobDetail")
    public JobDetail jobDetail() {
        // create a instance of interface JobDetail and return
        return JobBuilder.newJob(QuartzJob.class)
                .withIdentity("jobName", "jobGroup")
                .storeDurably()
                .build();
    }
 
    /**
     * 普通的触发器，此处也可用Cron储发器实现
     * @param jobDetail
     * @return
     */
    @Bean("simpleTrigger")
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetail jobDetail) {
 
        SimpleTriggerFactoryBean simpleTriggerFactoryBean = new SimpleTriggerFactoryBean();
        simpleTriggerFactoryBean.setJobDetail(jobDetail);
        simpleTriggerFactoryBean.setStartDelay(0);
        simpleTriggerFactoryBean.setRepeatInterval(1000);
 
        return simpleTriggerFactoryBean;
 
    }
 
    /**
     * 配置调度容器
     * @param simpleTrigger
     * @return
     */
    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactoryBean(Trigger simpleTrigger) {
 
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //用于Quartz集群，QuartzScheduler启动时会更新已存在的Job
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //延时启动，应用启动1秒后
        schedulerFactoryBean.setStartupDelay(1);
        //注册触发器
        schedulerFactoryBean.setTriggers(simpleTrigger);
 
        return schedulerFactoryBean;
 
    }
 
}